import { ProTable, type ProColumns } from "@ant-design/pro-components";
import { Component, type ChangeEvent } from "react";

import request from "@/utils/request";
import { Button } from "antd";
import * as XLSX from "xlsx";

// @ts-ignore
import ExportExcel from "js-export-excel";

export default class Role extends Component {
  columns: ProColumns<Role.Item>[] = [
    { title: "Id", dataIndex: "id" },
    { title: "名称", dataIndex: "name" },
    { title: "标识", dataIndex: "label" },
  ];
  list: Role.Item[] = [];

  handleDownloadOne = () => {
    const sheetHeader = this.columns.map((item) => item.title);
    const sheetHeaderKey = this.columns.map((item) => item.dataIndex);

    const sheetData = this.list.map((item) =>
      // @ts-ignore
      sheetHeaderKey.map((key) => item[key])
    );

    console.log("sheetHeader", sheetHeader);
    console.log("sheetHeaderKey", sheetHeaderKey);
    console.log("list", this.list);
    console.log("sheetData", sheetData);

    const excel = new ExportExcel({
      // 配置项
      fileName: "abcd",
      datas: [
        {
          sheetHeader,
          sheetData,
        },
      ],
    });

    excel.saveExcel();
  };

  // 借鉴 vue-element-admin 里面的代码
  handleDownloadTwo = () => {
    const sheetHeader = this.columns.map((item) => item.title);
    const sheetHeaderKey = this.columns.map((item) => item.dataIndex);
    const sheetData = this.list.map((item) =>
      // @ts-ignore
      sheetHeaderKey.map((key) => item[key])
    );

    // 引入 vendor/Export2Excel.js 这个模块
    // @ts-ignore
    import("@/vendor/Export2Excel").then((excel) => {
      excel.export_json_to_excel({
        header: sheetHeader, // 头行
        data: sheetData, // 数据
        filename: "aaa", // 文件名
        autoWidth: true, // 是否自动适应宽度
        bookType: "xlsx", // 文件类型
      });
    });
  };

  handleChange = (event: ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files;
    const file = files?.[0];

    // 创建一个 FileReader 实例
    const fileReader = new FileReader();
    // 调用 fileReader.readB
    fileReader.readAsBinaryString(file!);
    // 监听 fileReader.onload 事件，获取到读取完成
    fileReader.onload = () => {
      // console.log(this.result);
      // console.log(fileReader.result);
      // 使用 XLSX.read() 获取一个 workbook
      const workbook = XLSX.read(fileReader.result, { type: "binary" });
      console.log("workbook", workbook);
      // 使用 XLSX.utils.sheet_to_json 将 sheet 对象转换成 json 格式的和数据
      const json = XLSX.utils.sheet_to_json(workbook.Sheets.SheetJS);
      console.log("JSON", json);
      // 后续想干嘛就继续操作即可。
    };
  };

  render() {
    const { columns } = this;

    return (
      <ProTable
        rowKey="id"
        search={false}
        columns={columns}
        toolBarRender={() => [
          <input key="file" type="file" onChange={this.handleChange} />,
          <Button key="one" onClick={this.handleDownloadOne}>
            导出One
          </Button>,
          <Button key="two" onClick={this.handleDownloadTwo}>
            导出Two
          </Button>,
        ]}
        request={async (params) => {
          const resp = await request<{
            list: Role.Item[];
            pagination: Common.Pagination;
          }>({
            url: "/admin/base/sys/role/page",
            method: "POST",
            data: {
              page: params.current, // 页码
              size: params.pageSize, // 每页显示条数
            },
          });
          this.list = resp.list;
          return {
            data: resp.list, // 表格的 dataSource
            total: resp.pagination.total, // 如果要实现后端分页，则必须传递该字段，否则它会已兄弟的 data 数组长度作为数据总条数
          };
        }}
      ></ProTable>
    );
  }
}
